Some side effects need cleanup for example Component A requests the API to get some data, but while making that asynchronous request, Component A is removed from the DOM (it’s unmounted). There is no need to complete that asynchronous request. We can clean up (cancel) the asynchronous request so that it’s not completed.
the cleanup function helps developers clean effects that prevent unwanted behaviours and optimize application performance.
It is a function of the useEffect hook that allows us to stop side effects that no longer need to be executed before our component is unmounted.
useEffect is built in such a way that we can return a function inside it and this return function is where the cleanup happens.
You need to fetch data in a component and set up a timer that updates state every second. How would you use useEffect and its cleanup to avoid the timer continuing after the component unmounts?
If you add an event listener inside useEffect but forget to return a cleanup function, what will happen when the component is removed from the DOM?
We have a chat widget that subscribes to a WebSocket in useEffect. The connection sometimes stays open after navigating away, causing duplicate messages. Walk me through how you'd fix it using a cleanup function.
During a recent sprint, a memory leak was reported in a component that polls an API every 5 seconds. Explain why the leak occurred and how you'd modify the useEffect to resolve it.
Our dashboard renders dozens of widgets, each using useEffect to start intervals and subscriptions. How would you design a pattern or custom hook to ensure all cleanups are reliable and don't impact performance?
We are refactoring a legacy class component that uses componentWillUnmount for cleanup into a functional component. What pitfalls should we watch for when translating the cleanup logic to useEffect, especially regarding stale closures?
The product team wants to introduce a global event bus that many components will subscribe to via useEffect. At scale, how would you structure the cleanup strategy to avoid memory leaks and ensure consistent unsubscription across teams?
Our organization is migrating a large codebase from class components to hooks. How would you establish guidelines or tooling to audit existing useEffect implementations for missing cleanup functions, and what architectural considerations would you raise?